#include "dav_main.h"
//
/*  Save file as dav_main.cpp  */
/*  incomming class name Dav_Main */
//
#include <QCloseEvent>
//
QPointer<Dav_Main> Dav_Main::_self = 0L;
//
Dav_Main* Dav_Main::self( QWidget* parent )
{
	if ( !_self )
	_self = new Dav_Main( parent );
	return _self;
}
//
Dav_Main::Dav_Main( QWidget* parent )
	: QMainWindow( parent )
{
	setupUi( this );
    wdir->setSortingEnabled(false);
    netopen = true;
    remoteconnecturl = QString(setter.value("lasturldav").toString());
    if (remoteconnecturl.size() < 3) {
    remoteconnecturl ="http://ciz.ch/";
    }
    setupTray();
    ResetHeader();
    TargetDirBuild = "";
    setAcceptDrops(true);
    wdir->setDragEnabled(false);
    wdir->setAcceptDrops(true);
    dirtree->setDragEnabled(false);
    dirtree->setAcceptDrops(false);
    wdir->setContextMenuPolicy( Qt::CustomContextMenu );
    setContextMenuPolicy( Qt::CustomContextMenu );
    connect(allreset, SIGNAL(clicked()), this, SLOT(ReloadNewBuild()));
    connect(davcdup, SIGNAL(clicked()), this, SLOT(CdUpfromDefault()));
    connect(dirtree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this , SLOT(AppendSub(QTreeWidgetItem*,int))); 
    connect(wdir, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this , SLOT(BigTreeCD(QTreeWidgetItem*,int)));
    connect(remotepath, SIGNAL(currentIndexChanged(QString)), this, SLOT(ChancheDir(QString))); 
    connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(GlobalContext(QPoint)));
    connect(wdir, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(GlobalContext(QPoint)));
    connect(actionWebDav_Setting, SIGNAL(activated()), this, SLOT(ConnectionReset()));
    connect(actionReload, SIGNAL(activated()), this, SLOT(ReloadActualDir()));
    connect(actionAbout_App, SIGNAL(activated()), this, SLOT(AboutOpen()));
    
    
    connect(actionDAV_Specifications, SIGNAL(activated()), this, SLOT(Link_A()));
    connect(actionQT_WebDav_HomePage, SIGNAL(activated()), this, SLOT(Link_B()));
    connect(actionAutor_Homepage , SIGNAL(activated()), this, SLOT(Link_C()));
    
    actioncatdock = dockWidget->toggleViewAction();
    actioncatdock->setIcon(QIcon(QString::fromUtf8(":/img/tree.png")));
    actioncatdock->setShortcut(tr("Ctrl+S"));
    menuSetting->addAction(actioncatdock);
    bhome->setDefaultAction(actioncatdock);
    
    
    ///////bhome->setIcon(QIcon(QString::fromUtf8(":/img/tree.png")));
    bhome->setIconSize(QSize(25, 25));
    
    //////////AutoReload();
    ConnectionReset();
    
}


void Dav_Main::GetDirRecursive(QString remotepath ,QString localpath )
{
        /* Gui_Info( NetworkDav * db , QString path , const QString mirrordir  ); */
        if (netopen) {
               if (remotepath.endsWith("/")) {
              /////QApplication::restoreOverrideCursor();
               gdownload = new  Gui_Info(dbdav,remotepath,localpath);   /* Gui_Info *gdownload; */
               SetNetworkEnable();
               gdownload->setWindowModality(Qt::ApplicationModal);
               gdownload->show();
               /* no connect nothing make all Gui_Info on closeevent */

               }
        }                   
}


void Dav_Main::BigTreeCD( QTreeWidgetItem * treeniro , int coolnummer )
{
            BigStreItem = treeniro;     
            QString active = treeniro->toolTip(0);
            const QString iddavunique = treeniro->toolTip(5);
            /* QTreeWidget dirtree small --  QTreeWidget wdir big    */
           if (active.endsWith("/")) {
                activedir = true;
                activefile = false; 
            QString timemodb = treeniro->toolTip(4);
            QString obname, totips, topame, lastmodtime;
            QString parentfind =  PathNameTree(active);
            /* QList<QTreeWidgetItem *> QTreeWidget::findItems ( const QString & text, Qt::MatchFlags flags, int column */
            treefolder = dirtree->findItems(parentfind,Qt::MatchRecursive,0); 
            
             
             for (int i=0;i<treefolder.size();i++) {
                  obname = QString(treefolder[i]->text(0));
                  lastmodtime = QString(treefolder[i]->text(1));
                  totips = QString(treefolder[i]->toolTip(1));
                  QTreeWidget *topi = treefolder[i]->treeWidget();
                    topame = QString(topi->objectName());
                 
                    if ( topame == "dirtree" and timemodb == totips ) {
                      //////////qDebug() << "#### topame ->" << topame; 
                      ///////////qDebug() << "#### findChildren ->" << obname;   
                      qDebug() << "#### findChildren ->" << totips;
                        
                        AppendSub(treefolder[i],0);
                        return;
                        ///////treefolder[i]->setSelected(true);
                        /////////treefolder[i]->setBackground(0,QBrush ( QColor(Qt::blue)));
                        ////////StreItem = treefolder[i];
                    } 
                  }
                } else {
                activedir = false;
                activefile = true;  
                OpenRemoteFile(active,iddavunique);
                }  
}



void Dav_Main::OpenRemoteFile( const QString fileremote , const QString iddavunique ) 
{
             QString nameid;
    
                      for ( int x = 0; x < treefile.size(); ++x ) {
                          if (!treefile[x]->IsDir()) { 
                            nameid = treefile[x]->Geturl();
                             if (nameid == fileremote || iddavunique == treefile[x]->GetTag()) {
                                 ///////////qDebug() << "#### trovato il file ######### doppio click!  ->" << nameid;
                                    treefile[x]->LocalOpen();
                                 
                             }
                               
                          }
                      }
    
    
}


/*

T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/default_file.png")),tr( "Open File \"%1\"" ).arg(activefilename),treefile[o],SLOT( LocalOpen() ) ); 

*/


void  Dav_Main::DavRootUrl()
{
   OpenDesktop(QUrl(Domain(remoteconnecturl)));
}



void Dav_Main::setupTray()
{
	mTray = new QSystemTrayIcon( this );
	// NOTE: Always have an icon set befor calling show()
    QString troicon;
#if defined Q_WS_MAC
troicon = QString::fromUtf8(":/img/mac.png");
#endif
#if defined Q_WS_WIN
troicon = QString::fromUtf8(":/img/win.png");
#endif
#if defined Q_WS_X11
troicon = QString::fromUtf8(":/img/linux.png");
#endif
	mTray->setIcon( QIcon(troicon));
    
TRicon = new QMenu(this);
TRicon->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "Open url %1 from last session" ).arg(Domain(remoteconnecturl)), this , SLOT( DavRootUrl() ) );
///////TRicon->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "Open WebDav root url %1" ).arg(Domain(remoteconnecturl)), this , SLOT( DavRootUrl() ) ); 
TRicon->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "New Connection" ), this , SLOT( ConnectionReset() ) );
TRicon->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "Minimized Screen" ), this , SLOT( showMinimized() ) );
TRicon->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "Maximized Screen" ), this , SLOT( showMaximized() ) );
TRicon->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "Open Local Mirror" ), this , SLOT( OpenMirrorLocal() ) );
TRicon->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "About App" ), this , SLOT( AboutOpen() ) );
#if defined Q_WS_MAC
TRicon->addAction(QIcon(QString::fromUtf8(":/img/mac.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
#if defined Q_WS_WIN
TRicon->addAction(QIcon(QString::fromUtf8(":/img/win.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
#if defined Q_WS_X11
TRicon->addAction(QIcon(QString::fromUtf8(":/img/linux.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
    
    
    if (netopen) {
       status = tr("WebDav Network free."); 
    } else {
      status = tr("WebDav Network waiting (on work)...."); 
    }
    
    
    
    
    
    mTray->setToolTip(tr("%1\nStatus from Webdav:\n\n").arg(status).arg(_PROGRAM_TITLE_));
	mTray->setContextMenu( TRicon );
	/////////connect(mTray, SIGNAL(activated(int)), this, SLOT(slotTrayActivated(int)));
	mTray->show();
}

void Dav_Main::slotTrayActivated(int reason)
{
    qDebug() << "#### slotTrayActivated ->" << reason;
    
    
	if (reason == QSystemTrayIcon::Trigger) {
		slotToggleVisibility();
    }
}

void Dav_Main::slotToggleVisibility()
{
	if(isHidden())
	{
		show();
		if(isMinimized())
		{
			if(isMaximized())
				showMaximized();
			else
				showNormal();
		}
		raise();
		activateWindow();
	}
	else
	{
		hide();
	}
}






void  Dav_Main::Link_A()
{
   OpenDesktop(QUrl("http://www.webdav.org/specs/rfc2518.html"));
}

void  Dav_Main::Link_B()
{
   OpenDesktop(QUrl("http://sourceforge.net/projects/qt-webdav/"));
}

void  Dav_Main::Link_C()
{
   OpenDesktop(QUrl("http://ciz.ch/"));
}




void  Dav_Main::AboutOpen()
{
    Gui_About *mani = new Gui_About(this);
    mani->show();
}


/*



*/




void Dav_Main::ConnectionReset()
{
     SetNetworkDisable();
     QApplication::restoreOverrideCursor();
     ResetHeader();
     davconnection = new Gui_Connection(this);
     davconnection->setWindowModality(Qt::ApplicationModal);
     davconnection->show();
    if (davconnection->exec() != QDialog::Accepted) {
        return;
    }
    QString dirorfile =  QString(setter.value("MirrorDir").toString());
    if (dirorfile.size() < 1) {
        davconnection->MirrA();
    }
    
    dirorfile =  QString(setter.value("MirrorDir").toString());
    if (dirorfile.size() < 1) {
    return;
    }
    netopen = false;
    SetNetworkEnable();
    Load_Connector();
}



void Dav_Main::Load_Connector()
{
    
    
    PendingToOpen = "";
    remoteconnecturl = davconnection->durl->text();
    setter.setValue("lasturldav",remoteconnecturl);
    //////TRicon->removeAction (QIcon(QString::fromUtf8(":/img/info.png")),tr( "Open WebDav root url %1" ).arg(Domain(remoteconnecturl)), this , SLOT( DavRootUrl() ) );
    
    
    dbdav = new NetworkDav(remoteconnecturl,davconnection->duser->text(),davconnection->dpass->text(),80);
    activedir = false;
    activefile = false; 
    DummyRoot = dbdav->DummiRoot();
    mod_dav_0 = new BaseDav(dbdav,this);
    connect(mod_dav_0, SIGNAL(WakeUpFromList(QString)), this , SLOT(NextList(QString)));
    connect(mod_dav_0, SIGNAL(BuildTreeFromRemote(QDomDocument,QString)), this , SLOT(BuildTree(QDomDocument,QString)));
    connect(mod_dav_0, SIGNAL(StatusPrint(QString)), this , SLOT(ShowStatusBar(QString)));
    connect(mod_dav_0, SIGNAL(StopCicleFull()), this , SLOT(SetResetMain()));
    connect(mod_dav_0, SIGNAL(ErrorBuil()), this , SLOT(ConnectionReset()));
    
    
    
     dirmsg->setText(QString("Base loaded on %1").arg(UmanTimeFromUnix2(QTime_Null() ) ));
    DefaultDir = "/";
    ////////////netopen = false;
    
    ChancheDir(DefaultDir);
    AutoReload();
}


void Dav_Main::AutoReload()
{
    if (netopen) {
       status = tr("WebDav Network free."); 
    } else {
      status = tr("WebDav Network waiting (on work)...."); 
    }
    
    qDebug() << "#### rete aperta domanda  ->" << netopen;
    int secondi = davconnection->reloadafter->value() * 1000;
    qDebug() << "#### ogni millisecondi  ->" << secondi;
    
    if (netopen) {
        ReloadActualDir();
        mTray->showMessage(_PROGRAM_TITLE_,tr("Autoreload.. Status from Webdav:\n%1\nYour Setting Reload each %2 Sec.").arg(status).arg(davconnection->reloadafter->value()),QSystemTrayIcon::Information,2500);
    }
    
    
    
    QTimer::singleShot(secondi, this, SLOT(AutoReload()));  
  
}


void Dav_Main::MainRenamedir(QString from , QString to )
{
    
    if (!from.endsWith("/")) {
    return;
    }
    
    if (!to.endsWith("/")) {
    return;
    }
    
    QString source = from.prepend(DummyRoot);
    source = source.replace("//","/");
    
    QString desti = to.prepend(DummyRoot);
    desti = desti.replace("//","/");
    qDebug() << "#### source ->" << source;
    qDebug() << "#### desti ->" << desti;
    
    if (netopen) {
               SetNetworkDisable();
               DavMove *mover = new DavMove(dbdav,source,desti);
               connect(mover, SIGNAL(WarningMsg(QString)), mod_dav_0 , SLOT(ShowMessageWarning(QString)));
               connect(mover, SIGNAL(MoveDirReady()), this, SLOT(ReloadActualDir()));
               return;
    }
}

/* QString(setter.value("LastDirRemote").toString()) */

void Dav_Main::ReloadActualDir()
{
        qDebug() << "#### ReloadActualDir ->" << DefaultDir;
        mod_dav_0->OpenDir(DefaultDir,true);
        SetNetworkDisable();
}

void Dav_Main::OneGetandOpen( QString remote , QString local )
{
    PendingToOpen = local;
    GrabFile(remote,local);
    
}
void Dav_Main::GrabFile( QString remote , QString local )
{
   
    if (remote.endsWith("/")) {
    return;
    }
    
    qDebug() << "#### DummyRoot ->" << DummyRoot;
    
    remote = remote.prepend(DummyRoot);
    remote = remote.replace("//","/");
    
     qDebug() << "#### GrabFile ->" << remote;
    
    
    if (PendingToOpen.size() < 2) {
    PendingToOpen = "";
    }
    if (netopen) {
               SetNetworkDisable();
               QApplication::restoreOverrideCursor();
               Dav_Get *grabber = new Dav_Get(dbdav,remote,local,this);
               connect(grabber, SIGNAL(WarningMsg(QString)), mod_dav_0 , SLOT(ShowMessageWarning(QString)));
               connect(grabber, SIGNAL(LoadGetFileReady()), this, SLOT(PendingFile()));
               return;
    }
}


void Dav_Main::PendingFile()
{
    ///////////qDebug() << "#### PendingFile ->" << PendingToOpen.size();
    SetNetworkEnable();
    if (PendingToOpen.size() > 0) {
        OpenDesktop(QUrl(PendingToOpen));
    }
    PendingToOpen = "";
}





void Dav_Main::ResetHeader()
{
    remotepath->clear();
    treefile.clear();
    cleandirlist.clear();
    OnCodafile.clear();
    OnCodadir.clear();
    wdir->clear();
    wdir->headerItem()->setText(0,tr("Item Name"));
    wdir->headerItem()->setText(1,tr("Wight"));
    wdir->headerItem()->setText(2,tr("Mime"));
    wdir->headerItem()->setText(3,tr("Created Time "));
    wdir->headerItem()->setText(4,tr("Last mod Time Local "));
    SendNewFile = false;
    dirtree->clear();
    dirtree->headerItem()->setText(0,tr("Path Name"));
    dirtree->headerItem()->setText(1,tr("Last Mod."));
    
    DownDir_RM(WORK_CACHEDIR);
    fwriteutf8(REQUESTSTREAM,"");  /* make dir if not exist on mirror or reset file to zero  */
    qt_unlink(REQUESTSTREAM);  /* remove file */
}




void Dav_Main::RemoveonMain( const  QString dir )
{
    qDebug() << "#### RemoveonMain ->" << dir;
    
    if (netopen) {
               if (dir.endsWith("/")) {
                QApplication::restoreOverrideCursor();
               gremove = new  Gui_Remove(dbdav,dir);
               SetNetworkEnable();
               gremove->setWindowModality(Qt::ApplicationModal);
               gremove->show();
               connect(gremove, SIGNAL(CloseDeleteAction(QString)), this, SLOT(TargetRebuildRoot(QString)));
               connect(gremove, SIGNAL(StayonLevel(QString)), this, SLOT(TargetRebuildRoot(QString)));
               return;
               } else {
                mod_dav_0->RemoveDirorFileDav(dir);
                SetNetworkDisable();
                return;
               }
    }
}



void Dav_Main::CdUponeLevel( QString dirups )
{
     qDebug() << "#### signal back from remove  ->" << dirups;
    ChancheDir(CDDirUp(dirups));
}

void Dav_Main::CdUpfromDefault()
{
    ChancheDir(CDDirUp(DefaultDir));
}

void Dav_Main::TargetRebuildRoot( QString dir )
{
    TargetDirBuild = dir;
    qDebug() << "#### TargetRebuildRoot  ->" << dir;
    ChancheDir("/");
}

void Dav_Main::TargetPendigDir()
{
    QString dir = DefaultDir;
    
    if ( TargetDirBuild == dir ) {
       TargetDirBuild = ""; 
       return;
    }
    return;
    
    int levelbuildet,leveltarget;
    
    /*   /a/b/s/c/s/v/f/   */
    /*   a/b/s/c/s/v/f   */
    /*   a/b   */
    
    QString tat = PeelEnding(TargetDirBuild);
    QStringList list_t = tat.split("/");
    leveltarget = list_t.size();
    
    qDebug() << "#### targetpelato  ->" << PeelEnding(TargetDirBuild);
     qDebug() << "#### leveltarget  ->" << leveltarget;
    qDebug() << "#### list_t  ->" << list_t;
    
    if (dir == "/") {
    levelbuildet = 1; 
    } else {
    QString now = PeelEnding(dir);
    QStringList list_d = now.split("/");
    levelbuildet = list_d.size() + 1 ;
        
       qDebug() << "#### targetpelato2  ->" << PeelEnding(dir);
     qDebug() << "#### leveltarget2  ->" << levelbuildet;
    qDebug() << "#### list_t2  ->" << list_d; 
        
        
    }
    
    QString nextdir = "/";
    
       for (int i = 0; i < levelbuildet; ++i) {
           nextdir.append(list_t.at(i));
       }
    nextdir.append("/");
    
    qDebug() << "#### NEXDIRTOBUIL XXXXXX ->" << nextdir;
    
    if (levelbuildet == 1 ) {
            if (nextdir.size() > 2) {
            mod_dav_0->OpenDir(nextdir,true);
            SetNetworkDisable();
            return;
            }
    }
    
    TargetDirBuild = ""; 
}





//


void Dav_Main::ReloadNewBuild()
{
    qDebug() << "#### ReloadNewBuild ->" << DefaultDir;
    ChancheDir("/");
}

void Dav_Main::ChancheDir( const QString dir )
{
    qDebug() << "#### ChancheDir ->" << DefaultDir;
    
    if (netopen) {
    DefaultDir = dir;
    mod_dav_0->OpenDir(DefaultDir,false);
    SetNetworkDisable();
    }
}













void Dav_Main::MakeNewFolder()
{
    bool ok;
    QStringList fileop;
    QStringList dirop;
    dirop.clear();
    fileop.clear();
    QString foldername = QInputDialog::getText(this, tr("Name of folder"),tr("Name:"), QLineEdit::Normal,tr("new folder"), &ok);
    if (ok and foldername.size() > 2) {
        qDebug() << "#### foldername ->" << foldername;
        dirop.append(foldername);
        mod_dav_0->ProcessVirtualMkDirList(dirop,DefaultDir);
        SetNetworkDisable();
        dirop.clear();
        return;
    }
    
}

/*

QMenu *TContext;
 QMenu *T_dir_Context;
 QMenu *T_file_Context;

    wdir->headerItem()->setText(0,tr("Item Name"));
    wdir->headerItem()->setText(1,tr("Wight"));
    wdir->headerItem()->setText(2,tr("Mime"));
    wdir->headerItem()->setText(3,tr("Created Time GMT from Server"));
    wdir->headerItem()->setText(4,tr("Last mod Time Local Time"));

*/


void Dav_Main::GlobalContext( const QPoint & pos  )
{
    
    if (!wdir->currentItem()) {
        qDebug() << "#### noitemcase no file no dir ->" << DefaultDir;
        TContext = new QMenu(this);
        TContext->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "Reload Dir" ), this , SLOT( ReloadActualDir() ) );
        TContext->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "Open Local Mirror" ), this , SLOT( OpenMirrorLocal() ) );
     TContext->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "New Folder" ),this,SLOT( MakeNewFolder() ) );
 #if defined Q_WS_MAC
TContext->addAction(QIcon(QString::fromUtf8(":/img/mac.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
#if defined Q_WS_WIN
TContext->addAction(QIcon(QString::fromUtf8(":/img/win.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
#if defined Q_WS_X11
TContext->addAction(QIcon(QString::fromUtf8(":/img/linux.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
TContext->exec(QCursor::pos());
        
    return;
    }
    activefile = false; 
    activedir = false;
    
    QTreeWidgetItem *niro = wdir->currentItem();
    
    QString active = niro->toolTip(0);
    
    if (active.size() > 0) {
    
      if (active.endsWith("/")) {
                activedir = true;
                activefile = false; 
      } else {
          
                activefile = true; 
                activedir = false;
      }
    }
    
    TContext = new QMenu(this);
    TContext->addAction(QIcon(QString::fromUtf8(":/img/info.png")),tr( "Reload Dir" ), this , SLOT( ReloadActualDir() ) );
    TContext->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "Open Local Mirror" ), this , SLOT( OpenMirrorLocal() ) );
    
 
    
    
    QString namelong, namesmall, namebig, localplace;
    uint locallastmod,remotlastmodtimes,localcreated;
    
    
    
    if (activedir) {
        QString activedirname = niro->text(0);
        QString activepathdir = niro->toolTip(0);
         T_dir_Context = new QMenu(tr("Dir operation \"%1\"").arg(activedirname),TContext);
         T_dir_Context->setIcon(QIcon(QString::fromUtf8(":/img/default_dir.png")));
         
         ///////T_dir_Context->addAction(QIcon(QString::fromUtf8(":/img/misc.png")),tr( "Mirror Dir setting" ),this,SLOT( ReloadActualDir() ) );
     
                          for ( int x = 0; x < treefile.size(); ++x ) {
                              if (treefile[x]->IsDir()) { 
                                      namebig = treefile[x]->Geturl();
                                      if (activepathdir == namebig) {
                                      remotlastmodtimes = treefile[x]->GetFileTimeRemote();
                                      TContext->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "Download recursive dir \"%1\"" ).arg(activedirname),treefile[x],SLOT( DownloadDirRecursive() ) );  
                                     
                                      TContext->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "Rename Dir to.. \"%1\"" ).arg(activedirname),treefile[x],SLOT( RenameFolder() ) );  
                                          
                                          
                                          
                                          
                                      TContext->addAction(QIcon(QString::fromUtf8(":/img/qtdelete.png")),tr( "Delete Dir \"%1\"" ).arg(activedirname),treefile[x],SLOT( RemoveDirRecursive() ) );  
                                          
                                      T_dir_Context->addAction(QIcon(QString::fromUtf8(":/img/settings.png")),tr( "Mirror Dir setting" ),treefile[x],SLOT( MirrorSetting() ) );
                                      T_dir_Context->addAction(QIcon(QString::fromUtf8(":/img/qtdelete.png")),tr( "Delete Dir \"%1\"" ).arg(activedirname),treefile[x],SLOT( RemoveDirRecursive() ) ); 
                                      T_dir_Context->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "Rename Dir to.. \"%1\"" ).arg(activedirname),treefile[x],SLOT( RenameFolder() ) );  
                                         
                                      }
                              }
                          }
         TContext->addAction(T_dir_Context->menuAction());
    }
    
    
    
    
    if (activefile) {
        QString activefilename = niro->text(0);
        QString activepathfile = niro->toolTip(0);
         T_file_Context = new QMenu(tr("File operation %1").arg(activefilename),TContext);
         T_file_Context->setIcon(QIcon(QString::fromUtf8(":/img/default_file.png")));
         ////////////////T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/misc.png")),tr( "Mirror Dir setting" ),this,SLOT( ReloadActualDir() ) );
        
        
                        for ( int o = 0; o < treefile.size(); ++o ) {
                              if (!treefile[o]->IsDir()) { 
                                      namebig = treefile[o]->Geturl();
                                      localplace = treefile[o]->LocalMirrorFileOrDir();
                                      if (activepathfile == namebig) {
                                      remotlastmodtimes = treefile[o]->GetFileTimeRemote();
                                      TContext->addAction(QIcon(QString::fromUtf8(":/img/qtdelete.png")),tr( "Delete File \"%1\"" ).arg(activefilename),treefile[o],SLOT( RemoveDirRecursive() ) ); 
                                          
                                      T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/default_file.png")),tr( "Open File \"%1\"" ).arg(activefilename),treefile[o],SLOT( LocalOpen() ) ); 
                                      T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/default_file.png")),tr( "Download File \"%1\"" ).arg(activefilename),treefile[o],SLOT( GettoLocal() ) );    
                                      T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/settings.png")),tr( "Mirror Dir setting" ),treefile[o],SLOT( MirrorSetting() ) );
                                      T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/qtdelete.png")),tr( "Delete File \"%1\"" ).arg(activefilename),treefile[o],SLOT( RemoveDirRecursive() ) ); 
                                      T_file_Context->addAction(QIcon(QString::fromUtf8(":/img/settings.png")),tr( "Mirror Dir setting" ),treefile[o],SLOT( MirrorSetting() ) );
                                      }
                              }
                          }
        
        TContext->addAction(T_file_Context->menuAction());
    
        
        
    }
   
    
    
TContext->addAction(QIcon(QString::fromUtf8(":/img/default_dir.png")),tr( "New Folder" ),this,SLOT( MakeNewFolder() ) );
#if defined Q_WS_MAC
TContext->addAction(QIcon(QString::fromUtf8(":/img/mac.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
#if defined Q_WS_WIN
TContext->addAction(QIcon(QString::fromUtf8(":/img/win.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
#if defined Q_WS_X11
TContext->addAction(QIcon(QString::fromUtf8(":/img/linux.png")),tr( "Exit" ), this , SLOT( close() ) );
#endif
TContext->exec(QCursor::pos()); 
    
    
    
    
    
    
}


















void Dav_Main::SideTree( QDomDocument xml , const QString DisplayPath )
{
     dirtree->clear();   /* QTreeWidget  */
    
     ItemDelegate *delegate = new ItemDelegate();
     dirtree->setItemDelegate(delegate); 
    
    
    
    
     dirtree->headerItem()->setText(0,tr("Path Name"));
     dirtree->headerItem()->setText(1,tr("Last Mod."));
     QDomDocument doc(xml);
     QDomElement root = doc.documentElement();
     QDomElement listdir = root.firstChildElement("ddir");
     
             while (!listdir.isNull()) {
             QString dirname = listdir.attribute("name","Error");
                 if ( dirname != "/" ) {
                     QString obname = PathNameTree(dirname);
                     QString qtid = listdir.attribute("id","Error");
                     uint lastmodti = direct_int(listdir.attribute("lastmod","Error"));
                     QTreeWidgetItem *iter5 = new QTreeWidgetItem(dirtree);
                     /////////////iter5->setObjectName(QString::fromUtf8(obname));
                     iter5->setText(0, obname );
                     
                     iter5->setText(1, UmanTimeFromUnix2( lastmodti ));
                     iter5->setToolTip(1,qtid);
                     
                     iter5->setToolTip(0, dirname );
                     iter5->setFlags ( Qt::ItemIsEnabled );
                     iter5->setStatusTip(0,tr("Click \"%1\" or expand to check if has Child...").arg(obname));
                     iter5->setIcon(0,IconMime(dirname));     
                 }
                listdir = listdir.nextSiblingElement("ddir");
              }
              
    dirtree->resizeColumnToContents (0);
    dirtree->resizeColumnToContents (1);
              
    
    
       //////connect(dirtree, SIGNAL(itemActivated(QTreeWidgetItem,int)), this , SLOT(AppendSub(QTreeWidgetItem,int)));
  
}


void Dav_Main::SideSubTree( QDomDocument xml , const QString DisplayPath )
{
    
     QDomDocument doc(xml);
     
     if (!StreItem) {
     ////////mod_dav_0->ShowMessageWarning(tr("Not Valid active tree...)"));
     return;  
     }
     
     QString active = StreItem->toolTip(0);
     int bibi = StreItem->childCount();
     QDomElement root = doc.documentElement();
     QDomElement listdir = root.firstChildElement("ddir");
     int trchild = 0;

             while (!listdir.isNull()) {
             QString dirname = listdir.attribute("name","Error");
                   QString obname = PathNameTree(dirname);
                   uint lastmodti = direct_int(listdir.attribute("lastmod","Error"));
                   QString qtid = listdir.attribute("id","Error");
                 
                 if ( dirname != active ) {
                 trchild++;
                 if (trchild <= bibi) {
                     QTreeWidgetItem *iter8 =  StreItem->child(trchild - 1);
                    ////////////// iter8->setObjectName(QString::fromUtf8(obname));
                     iter8->setText(0, obname );
                     iter8->setText(1, UmanTimeFromUnix2( lastmodti ));
                     iter8->setToolTip(1,qtid);
                     iter8->setToolTip(0, dirname );
                     iter8->setStatusTip(0,tr("Click \"%1\" or expand to check if has Child...").arg(obname));
                 } else {
                 QTreeWidgetItem *iter5 = new QTreeWidgetItem(StreItem);
                 ////////////iter5->setObjectName(QString::fromUtf8(obname));
                 iter5->setText(0, obname );
                 iter5->setText(1, UmanTimeFromUnix2( lastmodti ));
                 iter5->setToolTip(1,qtid);
                 iter5->setToolTip(0, dirname );
                 iter5->setFlags ( Qt::ItemIsEnabled );
                 iter5->setIcon(0,IconMime(dirname));
                 iter5->setStatusTip(0,tr("Click \"%1\" or expand to check if has Child...").arg(obname));
                 }
                 
                 }
                listdir = listdir.nextSiblingElement("ddir");
              }
    
    
       bibi = StreItem->childCount();
              if (bibi > 0) {
                  StreItem->setExpanded(true);
              }
              
    dirtree->resizeColumnToContents (0);
    dirtree->resizeColumnToContents (1);
              
       
    
}









void Dav_Main::AppendSub( QTreeWidgetItem * treeniro , int coolnummer )
{
            StreItem = treeniro;     
            QString active = treeniro->toolTip(0);
            if (active != "/") {
            ChancheDir(active);
            } 
            
}

/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/
/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/
/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/
/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/

void Dav_Main::BuildTree( QDomDocument xml , const QString DisplayPath )
{
    netopen = false;
    QDomDocument doc(xml);
    int countitemondir = 0;
    /////////////////////asdir->setText(QString("From module.. %1").arg(DisplayPath));
    setter.setValue("LastDirRemote",DisplayPath);
    
    SendNewFile = false;
    
    if (DisplayPath !="") {
    DefaultDir = DisplayPath;
    } else { 
    ////////////asdir->setText(QString("Error from module.. null dir back %1!!!").arg(DisplayPath));  
    return;
    }
    
    if (DisplayPath == "/") {
     SideTree(xml,DisplayPath);   
    } else {
     SideSubTree(xml,DisplayPath);  
    }
    
    QStringList incommingdir;
    incommingdir.clear();
    treefile.clear();
     
    //////ItemDelegate *delegate = new ItemDelegate();
    //////wdir->setItemDelegate(delegate); 
     
    wdir->setSortingEnabled(false);
    wdir->clear();
    wdir->headerItem()->setText(0,tr("Item Name"));
    wdir->headerItem()->setText(1,tr("Wight"));
    wdir->headerItem()->setText(2,tr("Mime"));
    wdir->headerItem()->setText(3,tr("Created Time "));
    wdir->headerItem()->setText(4,tr("Last mod Time Local "));
    
    
    
    
     int remotefiletimeunixdir;
     int remotefileticreatedir;
     
     QDomElement root = doc.documentElement();
    
   
    
    
     int loidir = 0;
    
     QDomElement listdir = root.firstChildElement("ddir");
     QDomElement listfile = root.firstChildElement("dfile");
        while (!listdir.isNull()) {
            QString qtid = listdir.attribute("id","Error");
            QString dirname = listdir.attribute("name","Error");
            if (!cleandirlist.contains(dirname) and dirname !="Error" ) {
            incommingdir.append(dirname);
            cleandirlist.append(dirname);   /* never clear this hystory */
            }
            loidir++;
            
            if (dirname != "/") {
            
                if ( loidir > 1 ) {
                
                 countitemondir++;                    
                
            remotefiletimeunixdir = direct_int(listdir.attribute("lastmod","Error"));
            remotefileticreatedir = direct_int(listdir.attribute("create","Error"));
             
            QString dsmallname = PathNameTree( dirname );
            FileManager *dir_ram = new FileManager(dsmallname,true,dirname,remotefiletimeunixdir,qtid,this);
            connect(dir_ram, SIGNAL(MainReFresh()),this, SLOT(ReloadActualDir()));
            connect(dir_ram, SIGNAL(RemoteDirRm(QString)), this , SLOT(RemoveonMain(QString)));      
            connect(dir_ram, SIGNAL(GrabtoMirrorDir(QString,QString)),this, SLOT(GetDirRecursive(QString,QString)));       
            connect(dir_ram, SIGNAL(OpenFileorDir(QUrl)), this , SLOT(OpenDesktop(QUrl)));    
            connect(dir_ram, SIGNAL(RenameRemotedir(QString,QString) ), this , SLOT(MainRenamedir(QString,QString) ));  
                               
                    
                    
                    
                    
            treefile.append(dir_ram);
                    
                    
            
                     QTreeWidgetItem *iter1 = new QTreeWidgetItem(wdir);
                      iter1->setText(0,  dsmallname );  
                      iter1->setText(1, "");
                      iter1->setText(2, listdir.attribute("mime","Error") );
                      iter1->setText(3, UmanTimeFromUnix2( remotefileticreatedir ) );
                      iter1->setText(4, UmanTimeFromUnix2( remotefiletimeunixdir ));
                      iter1->setIcon(0,IconMime(dirname));
            
                      iter1->setToolTip(0, dirname );
                      iter1->setToolTip(1, dsmallname );
                      iter1->setToolTip(2, dsmallname );
                      iter1->setToolTip(3, dsmallname );
                      iter1->setToolTip(4, qtid );
                }
            
            }
                      
            
           listdir = listdir.nextSiblingElement("ddir");
        }
        
        
         while (!listfile.isNull()) {
    
                      QTreeWidgetItem *iter2 = new QTreeWidgetItem(wdir);
                      QString dfilename = listfile.attribute("name","Error");
                      countitemondir++; 
                      QString qtifid = listfile.attribute("id","Error");
                      
                      QString smallname = PathNameTree( dfilename );
                      
                      remotefiletimeunixdir = direct_int(listfile.attribute("lastmod","Error"));
                      remotefileticreatedir = direct_int(listfile.attribute("create","Error"));
             
                      FileManager *file_ram = new FileManager(smallname,false,dfilename,remotefiletimeunixdir,qtifid,this);
                      connect(file_ram, SIGNAL(MainReFresh()),this, SLOT(ReloadActualDir()));
                      connect(file_ram, SIGNAL(RemoteDirRm(QString)), this , SLOT(RemoveonMain(QString)));
                      connect(file_ram, SIGNAL(OpenFileorDir(QUrl)), this , SLOT(OpenDesktop(QUrl)));   
                      connect(file_ram, SIGNAL(GrabandOpen(QString,QString)), this , SLOT(OneGetandOpen(QString,QString)));
                      connect(file_ram, SIGNAL(OneGetAppend(QString,QString)), this , SLOT(GrabFile(QString,QString)));
                      treefile.append(file_ram);
   
                      iter2->setText(0,smallname);  
                      iter2->setToolTip(0, dfilename );
                      iter2->setToolTip(1, smallname );
                      iter2->setToolTip(2, smallname );
                      iter2->setToolTip(3, smallname );
                      iter2->setToolTip(4, qtifid );
                      iter2->setText(1,listfile.attribute("byte","Error"));
                      iter2->setText(2, listfile.attribute("mime","Error") );
                      iter2->setText(3, UmanTimeFromUnix2( remotefileticreatedir ) );
                      iter2->setText(4, UmanTimeFromUnix2( remotefiletimeunixdir ) );
                      iter2->setIcon(0,IconMime(smallname));
                      
           listfile = listfile.nextSiblingElement("dfile");
        }
    
        
    wdir->resizeColumnToContents (0);
    wdir->resizeColumnToContents (1);
    wdir->resizeColumnToContents (2);
    wdir->resizeColumnToContents (3);
    wdir->resizeColumnToContents (4);
        
        
      remotepath->clear();
      remotepath->addItems( cleandirlist );    


         for (int i = 0; i < cleandirlist.size(); ++i) {
          QString passo = cleandirlist.at(i);
             if (passo == DisplayPath) {
                 remotepath->setCurrentIndex(i);
             }

     }
   
   netopen = false;
   SendNewFile = false;
   SetNetworkEnable();
   dirmsg->setText(QString("Loaded on %1").arg(UmanTimeFromUnix2(QTime_Null() ) ));
     
     
     if (countitemondir == 0 ) {
        mTray->showMessage(_PROGRAM_TITLE_,tr("Tip...\nDrag File or Dir to MainWindow\nto upload to server."),QSystemTrayIcon::Information,5000); 
         
     }
     
     
    QSound bells(":/img/receive.wav");
           bells.setLoops(5);
    bells.play();
     
     
    
}


/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/
/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/
/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/
/* ############################# MAIN SCREEN DIR AND FILES ###############################################*/






QIcon Dav_Main::IconMime( QString name )
{
    QString imageicon;
    name = name.toLower();
    
    if (name.endsWith("/")) {
       imageicon = QString::fromUtf8(":/img/default_dir.png"); 
    } else if (name.endsWith(".png")) {
       imageicon = QString::fromUtf8(":/img/pictures.png"); 
    }  else if (name.endsWith(".jpg")) {
       imageicon = QString::fromUtf8(":/img/pictures.png"); 
    } else if (name.endsWith(".jpeg")) {
       imageicon = QString::fromUtf8(":/img/pictures.png"); 
    }  else if (name.endsWith(".gif")) {
       imageicon = QString::fromUtf8(":/img/pictures.png"); 
    } else if (name.endsWith(".tif")) {
       imageicon = QString::fromUtf8(":/img/pictures.png"); 
    } else if (name.endsWith(".tiff")) {
       imageicon = QString::fromUtf8(":/img/pictures.png"); 
    } else {
      imageicon = QString::fromUtf8(":/img/default_file.png"); 
    }
    QIcon actual(imageicon);
	return actual;
}



QIcon Dav_Main::IconMimeMarker( QString name )
{
    QString imageicon;
    name = name.toLower();
    
    if (name.endsWith("/")) {
       imageicon = QString::fromUtf8(":/img/default_dir_up.png"); 
    } else if (name.endsWith(".png")) {
       imageicon = QString::fromUtf8(":/img/pictures_up.png"); 
    }  else if (name.endsWith(".jpg")) {
       imageicon = QString::fromUtf8(":/img/pictures_up.png"); 
    } else if (name.endsWith(".jpeg")) {
       imageicon = QString::fromUtf8(":/img/pictures_up.png"); 
    }  else if (name.endsWith(".gif")) {
       imageicon = QString::fromUtf8(":/img/pictures_up.png"); 
    } else if (name.endsWith(".tif")) {
       imageicon = QString::fromUtf8(":/img/pictures_up.png"); 
    } else if (name.endsWith(".tiff")) {
       imageicon = QString::fromUtf8(":/img/pictures_up.png"); 
    } else {
      imageicon = QString::fromUtf8(":/img/default_file_up.png"); 
    }
    QIcon actual(imageicon);
	return actual;
}


void Dav_Main::ShowStatusBar(QString msg)
{
    if (msg.size() > 1 ) {
    statusBar()->showMessage(msg,5000);  
    } else {
    statusBar()->showMessage(tr("Ready"));
    }
}




void Dav_Main::SetResetMain()
{  
  netopen = false;
  allreset->setEnabled(netopen);
  ////////asdir->setText(DefaultDir);
   
  ShowStatusBar(tr("Error Action..."));
  QApplication::restoreOverrideCursor();
  QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
}








void Dav_Main::dragEnterEvent(QDragEnterEvent *event)
{
  event->acceptProposedAction();
}

void Dav_Main::dropEvent(QDropEvent *event)
{

if (!netopen) {
    /* un' altra operazione in corso */
    return;
}

     OnCodadir.clear();
     OnCodafile.clear();







    
    if(event && event->mimeData()) {
        const QMimeData *data = event->mimeData();
        QStringList urlmixed;
        urlmixed.clear();
        QStringList dirmixed;
        dirmixed.clear();
        QList<QUrl> urlelist;
           if (data->hasUrls()) {
                  urlelist = data->urls(); 
               for ( int i = 0; i < urlelist.size(); ++i ) { 
                  QUrl gettyurl(urlelist.at(i));
                     if (gettyurl.isValid()) {
                         QString shema = gettyurl.scheme();
                               ////////////qDebug() << "### shema " << shema; 
                         if (shema == "file") {
                             QString localfileupsgo = gettyurl.toLocalFile();
                             
                             if (is_file(localfileupsgo)) {
                             urlmixed.append(localfileupsgo);  
                                 qDebug() << "### file " << localfileupsgo;
                             }
                               QDir diro(localfileupsgo);
                               if (diro.exists()) {
                                dirmixed.append(localfileupsgo);
                                   qDebug() << "### dirs " << localfileupsgo;
                               }
                         }
                      }
               }
               SendUpPutList(urlmixed,dirmixed);
               return;
           }
           
       }
}



void Dav_Main::SendUpPutList( QStringList localfiles , QStringList localdirs )
{
     /////////SetNetworkDisable();
qDebug() << "### SendUpPutList dir...." << DefaultDir;
qDebug() << "### SendUpPutList dirl...." << localdirs;
qDebug() << "### SendUpPutList fill...." << localfiles;
    
     OnCodadir.clear();
     OnCodafile.clear();
    
     if (localdirs.size() > 0 ) {
        /* QStringList OnCodadir;  save now here to process first localfiles*/
        for (int x = 0; x < localdirs.size(); ++x) {
            OnCodadir.append(localdirs.at(x));
        }
     }
     OnCodafile.clear();
     
    if (localfiles.size() > 0) {
    /* DefaultDir */
         mod_dav_0->ProcessPutList(localfiles,DefaultDir);
         SetNetworkDisable();
         QApplication::restoreOverrideCursor();
         //////hide();
        return;
    }
     
    if (OnCodadir.size() > 0 ) {
       NextList(DefaultDir);
       return;        
    }
    //////////SetNetworkEnable();
}



void Dav_Main::NextList( QString DirReload )
{
    qDebug() << "### NextList ............." << DirReload;
    DefaultDir = DirReload;
    ////////////setter.setValue("LastDirRemote",DirReload);
    //////mod_dav_0->ShowMessageWarning( QString("Main Load dir %1").arg(DirReload) );
    //////////SetNetworkDisable();
    
    if (OnCodadir.size() > 0 ) {
        mod_dav_0->ProcessMkDirList(OnCodadir,DefaultDir);
        OnCodadir.clear();  /* remove list to next */
        OnCodafile.clear();
        SendNewFile = false;
        SetNetworkDisable();
        return;
    }
    /* next list get mkcol ecc....       ProcessPutList( QStringList xx , QString DirReload ); */
    SetNetworkEnable();
    ///////SendNewFile = true;
    ReloadActualDir();
    
    if (this->isHidden()) {
        this->setVisible(true);
    }
    
   ///////////// mod_dav_0->OpenDirRealTime(DirReload);
}


void Dav_Main::SetNetworkEnable()
{  
  netopen = true;
  allreset->setEnabled(netopen);
    
    davcdup->setEnabled(netopen);
    
  ////////asdir->setText(DefaultDir);
   
  ShowStatusBar(tr("WebDav Server wait your next action..."));
  QApplication::restoreOverrideCursor();
  QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
}





void Dav_Main::SetNetworkDisable()
{  
   netopen = false;
   //////SendNewFile = false;    
   /////////asdir->setText(DefaultDir);
     ////////////asdir->setText(QString("SetNetworkDisable.. %1").arg(DefaultDir));
   allreset->setEnabled(netopen);
    davcdup->setEnabled(netopen);
   ShowStatusBar(tr("Wait get info from WebDav Server"));
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
}

void Dav_Main::closeEvent( QCloseEvent* e )
{
	e->accept();
    delete mTray;
    qApp->quit();
    
}




void Dav_Main::OpenMirrorLocal()
{
	QString dirsave =  QString(setter.value("MirrorDir").toString());
    OpenDesktop(QUrl(dirsave));
}



void Dav_Main::OpenDesktop( QUrl loc )
{  
    
    qDebug() << "### OpenDesktop ............." << loc;
    qDebug() << "### OpenDesktop ............." << loc.toString();
    
    
#if defined Q_WS_WIN
QString winbuh = DesktopFile(loc.toString());
    
    qDebug() << "### winbuh ............." << winbuh;
    
    bool wr = QDesktopServices::openUrl(QUrl(winbuh));
    if (!wr) {
    QMessageBox::warning(this, tr("Error"),tr("Unable to open file or dir  %1").arg(loc.toString()));
    }
return;
#endif
    
    
     bool r = QDesktopServices::openUrl(loc);
    if (!r) {
    QMessageBox::warning(this, tr("Error"),tr("Unable to open file or dir  %1").arg(loc.toString()));
    }
}
























